<?php
/**
 * 图床上传
 * Created by PhpStorm.
 * User: jifee8505
 * Date: 2018/4/2
 * Time: 上午11:47
 */

namespace common\behaviors;

use Yii;
use yii\base\Behavior;
use yii\web\Response;
use yii\web\UploadedFile;

include_once('/home/worker/7659_php_sdk/pic_storage/pic_client.php');

class PicStorageBehavior extends Behavior
{

    public $param = [];
    public $model;

    public function uploadFile()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $this->param = Yii::$app->request->getBodyParams();

        $modelClass = new $this->model;
        $fileInstance = UploadedFile::getInstance($modelClass, $this->param['file']);

        if (!empty($fileInstance)) {

            $picClient = \PicClient::getInstance();
            $picClient->setToken("7659_gaming", "6y[Rc9Iqbysax+");
            if (!empty($this->detectFileType($fileInstance->extension))) {
                $res = $picClient->process($fileInstance->tempName);
            } else {
                $res = $picClient->smallfile($fileInstance->tempName, ['ext' => $fileInstance->extension]);
            }

            if ($res['errno'] !== 0) {
                throw new \Exception($res['errmsg']);
            }

            $param = [
                'error' => $fileInstance->error,
                'name' => $fileInstance->name,
                'size' => $fileInstance->size,
                'tempName' => $fileInstance->tempName,
                'type' => $fileInstance->type,
                'link' => self::getLink($res['data']),
            ];
            return ['result' => 'success', 'message' => Yii::t('app', 'Success'), 'data' => $param];

        }

        throw new \Exception(Yii::t('app', 'Error'));
    }


    protected $fileTypes = [
        'image' => 'png|jpg|jpeg|gif',
    ];

    protected function detectFileType($extension)
    {
        foreach ($this->fileTypes as $type => $regex) {
            if (preg_match("/^($regex)$/i", $extension) !== 0) {
                return $type;
            }
        }
        return false;
    }

    static function getLink($fileInfo)
    {
        $rand = array_rand($fileInfo['hosts'], 1);
        return $fileInfo['hosts'][$rand] . $fileInfo['uri'];
    }
}